package com.example.demo.config;

import com.example.demo.job.MyJob;
import com.example.demo.job.MyJob2;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.quartz.CronTriggerFactoryBean;
import org.springframework.scheduling.quartz.JobDetailFactoryBean;
import org.springframework.scheduling.quartz.SchedulerFactoryBean;
import org.springframework.scheduling.quartz.SimpleTriggerFactoryBean;

/**
 * @author keyer
 * @Name : com.example.demo.config.QuartzConfig
 * @Description : 描述
 * Created by cyd on 2021-03-19 11:21:09
 */
@Configuration
public class QuartzConfig {
    @Bean(name = "Job1")
    public JobDetailFactoryBean Job1() {
        JobDetailFactoryBean jobDetailFactory = new JobDetailFactoryBean();
        //关联我们定义的Job类
        jobDetailFactory.setJobClass(MyJob.class);
        return jobDetailFactory;
    }

    @Bean(name = "Job2")
    public JobDetailFactoryBean Job2() {
        JobDetailFactoryBean jobDetailFactoryBean = new JobDetailFactoryBean();
        jobDetailFactoryBean.setJobClass(MyJob2.class);
        return jobDetailFactoryBean;
    }

    /**
     * 设置job1的定时器  类型为简单定时器 SimpleTrigger
     *
     * @param jobDetailFactory
     * @return
     */
    @Bean(name = "cronJob1")
    public SimpleTriggerFactoryBean cronJob1(@Qualifier("Job1") JobDetailFactoryBean jobDetailFactory) {
        SimpleTriggerFactoryBean simpleTriggerFactory = new SimpleTriggerFactoryBean();
        simpleTriggerFactory.setJobDetail(jobDetailFactory.getObject());
        //设置间隔时间
        simpleTriggerFactory.setRepeatInterval(2000);
        //设置重复次数
        simpleTriggerFactory.setRepeatCount(20);
        return simpleTriggerFactory;
    }

    /**
     * 设置job2的定时器  用cron模式
     */
    @Bean(name = "cronJob2")
    public CronTriggerFactoryBean cronJob2(@Qualifier("Job2") JobDetailFactoryBean jobDetailFactoryBean) {
        CronTriggerFactoryBean cronTriggerFactoryBean = new CronTriggerFactoryBean();
        cronTriggerFactoryBean.setJobDetail(jobDetailFactoryBean.getObject());
        cronTriggerFactoryBean.setCronExpression("0/5 * * * * ?");
        return cronTriggerFactoryBean;
    }

    /**
     * 将SimpleTrigger，cornTrigger 分别加入SchedulerFactoryBean
     *
     * @param
     * @return
     */
    @Bean
    public SchedulerFactoryBean schedulerFactoryBean(@Qualifier("cronJob1") SimpleTriggerFactoryBean Job1
            , @Qualifier("cronJob2") CronTriggerFactoryBean Job2) {
        SchedulerFactoryBean schedulerFactory = new SchedulerFactoryBean();
        //一次可以加多个任务定时器
        schedulerFactory.setTriggers(Job1.getObject(), Job2.getObject());
        return schedulerFactory;
    }
}
